package com.vinjune.bigdata.bloomfilter.redis.support;

import com.vinjune.bigdata.bloomfilter.redis.BloomRedisService;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Pipeline;
import redis.clients.jedis.Response;

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * Created by 000376 on 2018/3/7.
 */

public class RedisStandaloneService implements BloomRedisService {
    private JedisPool pool = null;

    public RedisStandaloneService(JedisPool pool) {
        this.pool = pool;
    }

    public <T> List<T> transactionallyDo(Consumer<Pipeline> f, String... watch) {
        return (List)this.safelyReturn((jedis) -> {
            Pipeline p = jedis.pipelined();
            if(watch.length != 0) {
                p.watch(watch);
            }

            p.multi();
            f.accept(p);
            Response exec = p.exec();
            p.sync();
            return (List)exec.get();
        });
    }

    public Long del(String key) {
        return (Long)this.safelyReturn((jedis) -> {
            return jedis.del(key);
        });
    }

    public Long expire(String cacheKey, int seconds) {
        return (Long)this.safelyReturn((jedis) -> {
            return jedis.expire(cacheKey, seconds);
        });
    }

    public Long expireAt(String key, long unixTime) {
        return (Long)this.safelyReturn((jedis) -> {
            return jedis.expireAt(key, unixTime);
        });
    }

    public <T> T safelyReturn(Function<Jedis, T> f) {
        Jedis jedis = this.pool.getResource();
        Throwable var3 = null;

        Object var4;
        try {
            var4 = f.apply(jedis);
        } catch (Throwable var13) {
            var3 = var13;
            throw var13;
        } finally {
            if(jedis != null) {
                if(var3 != null) {
                    try {
                        jedis.close();
                    } catch (Throwable var12) {
                        var3.addSuppressed(var12);
                    }
                } else {
                    jedis.close();
                }
            }

        }

//        return (T)var4;
        return var4;
    }


    public void destroy() {
        this.pool.destroy();
    }
}
